package com.ruoyi.tongban.utils;


import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.Base64;
import com.qiniu.util.UrlSafeBase64;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.ISysConfigService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URLDecoder;

/**
 * @Desc 七牛云存储
 * @Author caiyanshan
 * @Date 2020/3/10 9:21
 **/
public class QiniuCloudUtil {

  private final static Logger logger = LoggerFactory.getLogger(QiniuCloudUtil.class);
  
  private static ISysConfigService iSysConfigService;
  
  private static ISysConfigService getSysConfig(){
    if(iSysConfigService == null){
      iSysConfigService = SpringUtils.getBean(ISysConfigService.class);
    }
    return iSysConfigService;
  }

  // 设置需要操作的账号的AK和SK
  private static String ACCESS_KEY = null;
  private static String SECRET_KEY = null;
  // 要上传的空间名
  private static String BUCKET_NAME = null;
  // 要显示的域名
  private static String DOMAIN = null;
  
  private static void init() {
    ACCESS_KEY = getSysConfig().selectConfigByKey("applets.qiniu.accesskey");
    SECRET_KEY = getSysConfig().selectConfigByKey("applets.qiniu.secret");
    BUCKET_NAME = getSysConfig().selectConfigByKey("applets.qiniu.bucketname");
    DOMAIN = getSysConfig().selectConfigByKey("applets.qiniu.domain");
    auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    flag = true;
  }

  // 密钥
  private static Auth auth = null;
  
  private static boolean flag = false;
  
  public static String upload64image(String key, String file64){
    if(!flag){
      init();
    }
/*    String file = "D:\\123.jpg";//图片路径
    FileInputStream fis = null;
    int l = (int) (new File(file).length());
    byte[] src = new byte[l];
    fis = new FileInputStream(new File(file));
    fis.read(src);
    // 将图片解码为Base64编码图片
    String file644 = Base64.encodeToString(src, 0);*/

    //int l = -1;
    String url = "http://upload-z2.qiniup.com/putb64/-1/key/"+ UrlSafeBase64.encodeToString(key);
    //非华东空间需要根据注意事项 1 修改上传域名
    
    
/*    String base64 = Base64ImageUtils.unSaleUrl(file64);
    String file644 = Base64.encodeToString(file64);*/
    String base = "";
    try {
      base = URLDecoder.decode(file64,"UTF-8");
      base = base.substring(base.indexOf( "," ) + 1);
    }catch (Exception e){
    
    }

    RequestBody rb = RequestBody.create(null, base);
    Request request = new Request.Builder().
            url(url).
            addHeader("Content-Type", "application/octet-stream")
            .addHeader("Authorization", "UpToken " + auth.uploadToken(BUCKET_NAME))
            .post(rb).build();
    System.out.println(request.headers());
    OkHttpClient client = new OkHttpClient();
    try{
      okhttp3.Response response = client.newCall(request).execute();
      
      System.out.println(response.body().string());
    }catch (Exception e){
    
    }
    return DOMAIN + key;
  }
  
  //上传
  public static JSONObject upload(InputStream inputStream, String fileName){
    if(!flag){
      init();
    }
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region2());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    try {
      String upToken = auth.uploadToken(BUCKET_NAME);
      try {
        Response response = uploadManager.put(inputStream, fileName, upToken, null, null);
        JSONObject result = JSONObject.parseObject(response.bodyString());
        if (null == result.get("error")) {
          result.put("key", DOMAIN + result.getString("key"));
          result.put("hash", DOMAIN + result.getString("hash"));
        }
        return result;
      } catch (QiniuException ex) {
        Response r = ex.response;
        logger.error(r.toString());
        try {
          System.err.println(r.bodyString());
        } catch (QiniuException ex2) {
          logger.error("上传出错：" + ex2);
        }
      }
    } catch (Exception e) {

    }
    return null;
  }
  
  
  //上传
  public static JSONObject uploadDemo(InputStream inputStream, String key, String bucketname, String domain, Auth auth) throws IOException {
    //构造一个带指定 Region 对象的配置类
    Configuration cfg = new Configuration(Region.region2());
    //...其他参数参考类注释
    UploadManager uploadManager = new UploadManager(cfg);
    //默认不指定key的情况下，以文件内容的hash值作为文件名
    try {
      String upToken = auth.uploadToken(BUCKET_NAME);
      try {
        Response response = uploadManager.put(inputStream, key, upToken, null, null);
        JSONObject result = JSONObject.parseObject(response.bodyString());
        if (null == result.get("error")) {
          result.put("key", DOMAIN + result.getString("key"));
          result.put("hash", DOMAIN + result.getString("hash"));
        }
        return result;
      } catch (QiniuException ex) {
        Response r = ex.response;
        logger.error(r.toString());
        try {
          System.err.println(r.bodyString());
        } catch (QiniuException ex2) {
          logger.error("上传出错：" + ex2);
        }
      }
    } catch (Exception e) {
    
    }
    return null;
  }
}



